Completed
Push — master ( d362a9...56faa4 )
by Mark
14s queued 11s
created

HasOne   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 33
dl 0
loc 45
rs 10
c 0
b 0
f 0
wmc 7

4 Functions

Rating   Name   Duplication   Size   Complexity  
A getRelationalFields 0 3 1
A setName 0 4 1
A setParentProperties 0 13 1
A getValueByParentKey 0 5 4
1
import Relation from "../Relation.js";
2
import {ModelStaticInterface} from "../../../JeloquentInterfaces";
3
import ForeignKey from "../Field/ForeignKey";
4
5
/**
6
 *
7
 */
8
export default class HasOne extends Relation {
9
10
    constructor(model: ModelStaticInterface) {
11
        super(model);
12
    }
13
14
    get originalValue(): unknown {
15
        return this.getValueByParentKey('originalPrimaryKey');
16
    }
17
18
    get value(): unknown {
19
        return this.getValueByParentKey('primaryKey');
20
    }
21
22
    getRelationalFields():Array<ForeignKey> {
23
        return [];
24
    }
25
26
    setName(): HasOne {
27
        this.foreignKey = `${this.$parent.snakeCaseClassName}_id`;
28
        return this;
29
    }
30
31
    protected setParentProperties(): HasOne {
32
        super.setParentProperties();
33
34
        Object.defineProperty(this.$parent,
35
            `has${this.model.className}`, {
36
                get: () => {
37
                    return this.value !== null;
38
                },
39
            }
40
        )
41
42
        return this;
43
    }
44
45
    private getValueByParentKey(parentProperty) {
46
        const keyIndex = this.model.getIndexByKey(this.foreignKey);
47
        return globalThis.Store.database().find(this.model.className,
48
            [...keyIndex.get(this.$parent[parentProperty])?.values() ?? []]
49
        ).first();
50
    }
51
}